package com.huitong.common.core.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.util.Collection;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * Stream流工具类
 *
 * @author fromdrowning
 * @date 2024/3/20 15:51
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class StreamUtils {

    /**
     * 拼接集合
     *
     * @param collection 需要转化的集合
     * @param function   拼接方法
     * @return 拼接后的集合
     */
    public static <E> String join(Collection<E> collection, Function<E, String> function) {
        return join(collection, function, ",");
    }

    /**
     * 拼接集合
     *
     * @param collection 需要转化的集合
     * @param function   拼接方法
     * @param delimiter  拼接符
     * @return 拼接后的集合
     */
    public static <E> String join(Collection<E> collection, Function<E, String> function, CharSequence delimiter) {
        if (CollUtil.isEmpty(collection)) {
            return StrUtil.EMPTY;
        }

        return collection.stream()
            .map(function)
            .filter(Objects::nonNull)
            .collect(Collectors.joining(delimiter));
    }
}
